﻿using JNPF.Basics.Models;
using JNPF.Data;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 菜单管理
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2017.09.20 
    /// </summary>
    internal class MenuService : DataFactory, MenuIService
    {
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<ModuleEntity>> GetList()
        {
            using (var db = this.Basic)
            {
                return await db.GetIQueryable<ModuleEntity>().OrderBy(o => o.SortCode).ToListAsync();
            }

        }
        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<ModuleEntity> GetInfo(string id)
        {
            using (var db = this.Basic)
            {
                return await db.GetEntityAsync<ModuleEntity>(m => m.Id == id);
            }
        }
        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="whereLambda">条件</param>
        /// <returns></returns>
        public async Task<bool> IsExist(Expression<Func<ModuleEntity, bool>> whereLambda)
        {
            using (var db = this.Basic)
            {
                return (await db.GetCountAsync(whereLambda) > 0);
            }

        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity">实体对象</param>
        public async Task Delete(ModuleEntity entity)
        {
            using (var db = this.Basic)
            {
                await db.BeginTransactionAsync();
                await db.DeleteAsync(entity);
                await db.DeleteAsync<ModuleButtonEntity>(m => m.ModuleId == entity.Id);
                await db.DeleteAsync<ModuleColumnEntity>(m => m.ModuleId == entity.Id);
                await db.DeleteAsync<ModuleDataAuthorizeEntity>(m => m.ModuleId == entity.Id);
                await db.CommitTransactionAsync();
            }
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Create(ModuleEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.InsertAsync(entity);
            }
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Update(ModuleEntity entity)
        {
            using (var db = this.Basic)
            {
                return await db.UpdateAsync(entity);
            }
        }

    }
}
